// utils/base64.js
const mimeTypes = {
  png: 'image/png',
  jpg: 'image/jpeg',
  jpeg: 'image/jpeg',
  gif: 'image/gif',
  webp: 'image/webp'
}

function getMimeType(ext) {
  return mimeTypes[ext.toLowerCase()] || 'application/octet-stream'
}

export function pathToBase64(path) {
  return new Promise((resolve, reject) => {
    if (process.env.UNI_PLATFORM.startsWith('mp-') || process.env.UNI_PLATFORM === 'app') {
      const fs = uni.getFileSystemManager()
      fs.readFile({
        filePath: path,
        encoding: 'base64',
        success: res => {
          try {
            const ext = path.split('.').pop()
            resolve(`data:${getMimeType(ext)};base64,${res.data}`)
          } catch (e) {
            reject(new Error('MIME类型错误: ' + e.message))
          }
        },
        fail: err => reject(new Error('文件读取失败: ' + err.errMsg))
      })
    } else if (process.env.UNI_PLATFORM === 'h5') {
      const xhr = new XMLHttpRequest()
      xhr.open('GET', path, true)
      xhr.responseType = 'blob'
      
      xhr.onload = function() {
        if (this.status === 200) {
          const reader = new FileReader()
          reader.onload = e => resolve(e.target.result)
          reader.onerror = () => reject(new Error('文件读取失败'))
          reader.readAsDataURL(this.response)
        } else {
          reject(new Error(`HTTP错误: ${this.status}`))
        }
      }
      xhr.onerror = () => reject(new Error('网络请求失败'))
      xhr.send()
    } else {
      reject(new Error('不支持的环境'))
    }
  })
}

export function base64ToPath(base64) {
  return new Promise((resolve, reject) => {
    try {
      const matches = base64.match(/^data:(.+?);base64,(.+)$/)
      if (!matches || matches.length !== 3) throw new Error('Base64格式错误')

      const mimeType = matches[1]
      const data = matches[2]
      const ext = mimeType.split('/')[1]?.split(';')[0] || 'png'

      if (process.env.UNI_PLATFORM.startsWith('mp-') || process.env.UNI_PLATFORM === 'app') {
        const fs = uni.getFileSystemManager()
        const filename = `${Date.now()}.${ext}`
        const filePath = `${uni.env.USER_DATA_PATH}/${filename}`

        fs.writeFile({
          filePath,
          data,
          encoding: 'base64',
          success: () => resolve(filePath),
          fail: err => reject(new Error('文件写入失败: ' + err.errMsg))
        })
      } else if (process.env.UNI_PLATFORM === 'h5') {
        const byteCharacters = atob(data)
        const byteArrays = new Uint8Array(byteCharacters.length)

        for (let i = 0; i < byteCharacters.length; i++) {
          byteArrays[i] = byteCharacters.charCodeAt(i)
        }

        const blob = new Blob([byteArrays], { type: mimeType })
        resolve(URL.createObjectURL(blob))
      } else {
        reject(new Error('不支持的环境'))
      }
    } catch (e) {
      reject(new Error('转换失败: ' + e.message))
    }
  })
}